package com.langsin.blog.service.impl;

import com.langsin.blog.dao.UserDao;
import com.langsin.blog.dao.impl.UserDaoImp;
import com.langsin.blog.domain.Roles;
import com.langsin.blog.domain.User;
import com.langsin.blog.service.UserService;
import org.junit.Test;

import java.util.Date;

public class UserServiceImp implements UserService {

    private UserDao userDao = new UserDaoImp();

    public int loginCheck(String account, String password) {
        if (this.userExist(account)) {
            if (password.equals((userDao.userSelectByAccount(account).getPassword()))) {
                return 1;
            } else {
                return 0;
            }
        } else {
            return -1;
        }
    }

    @Test
    public void test() {
        this.registCheck("root1", "root", "root", "247820858@qq.com", "root");
//        System.out.println(this.registCheck("user1","user","user1","2036715016@qq.com","user"));
    }

    public boolean registCheck(String account, String password, String nickname, String email, String roles) {
        if (this.userExist(account)) {
            return false;
        } else {
            User user = new User();
            user.setAccount(account);
            user.setPassword(password);
            user.setEmail(email);
            user.setNickname(nickname);
            user.setCreateTime(new Date());
            Roles rolesRoot = null;
            Roles rolesUser = null;
            if ("root".equals(roles)) {
                rolesRoot = new Roles();
                rolesRoot.setName("root");
                user.setRoles(rolesRoot);
            } else if ("user".equals(roles)) {
                rolesUser = new Roles();
                rolesUser.setName("user");
                user.setRoles(rolesUser);
            }
            userDao.userAdd(user);
            return true;
        }
    }

    public boolean userModify(String account, String prop, String value) {
        User user = this.userGet(account);
        userDao.userModify(user.getId(), prop, value);
        return false;
    }

    public User userGet(String account) {
        User user = userDao.userSelectByAccount(account);
        return user;
    }

    public boolean userExist(String account) {
        if (userDao.userSelectByAccount(account) == null) {
            return false;
        } else {
            return true;
        }
    }
}
